# coding:utf-8
class Admin::ActivitiesController < AdminController

  set_tab :developers
  set_tab :activities, :sub_nav
  before_filter :setup, only: [:index]

  def index
    params[:activity] ||= {}
    @tables = ActiveRecord::Base.connection.tables.collect{|t| t.classify.constantize rescue nil }.compact.collect(&:name).sort - without_paper_trail
    if params[:activity][:item_type].blank?
      @error = '请选择表'
    else
      model = params[:activity][:item_type].constantize
      @fields = model.attribute_names
      # if query for field
      if params[:activity][:field].present? && params[:activity][:value].present?
        # check whether the field exists
        if @fields.include?(params[:activity][:field])
          is_fuzzy = params[:activity][:value].start_with?('%') || params[:activity][:value].end_with?('%')
          operator = is_fuzzy ? 'like' : '='
          model = model.where("#{params[:activity][:field]} #{operator} ?", params[:activity][:value])
        else
          @tip = '未找到' + params[:activity][:field] + ',已忽略,可用列:' + @fields.join(',')
        end

        rows = model.order('id desc').collect(&:id)
        @versions = PaperTrail::Version.where(item_type: params[:activity][:item_type], item_id: rows).order("id desc")
      else
        @versions = PaperTrail::Version.where(item_type: params[:activity][:item_type]).order("id desc")
      end

      # if query for start date
      if params[:activity][:start_date].present?
        @versions = @versions.where(["created_at >= ?", params[:activity][:start_date]])
      end
      if params[:activity][:end_date].present?
        @versions = @versions.where(["created_at < ?", 
          1.days.since(Time.zone.parse(params[:activity][:end_date])).strftime("%Y-%m-%d")])
      end
      
      begin
        if @versions.empty?
          @error = '未找到记录'
        end
      rescue ActiveRecord::StatementInvalid => e
        @error = '数据库查询错误:' + e.message
      end

    end
  end

  private

    def setup
      @ways = ["日志管理", "操作日志"]
      @left_panel = "layouts/developer_left_panel"
    end

    def without_paper_trail
      %w{Version}
    end

end
